import React,{useState,useEffect} from "react";
import { useNavigate } from "react-router-dom";
import {
    $getSelfInformation,
    $getMinePosts,
    $getFollowCount,
    $getTagList,
    $getSearchTagList,
    $addnewTag, $deletenewTag,$ModifySelfInfo,$ModifyAvater
} from "../../api/mineapi";
import {
    CloseCircleOutlined,
    DownOutlined,
    ManOutlined,
    WomanOutlined,
    SettingOutlined,
    PlusOutlined
} from '@ant-design/icons';
import {AutoComplete, Button, Drawer, Form, Input} from "antd";
import UploadImg from "../../uploadImg/uploadImg";
import Post from "../../components/post/post";
import { $getImg } from "../../api/getImgapi";
import {Modal} from "antd";
import UploadImg1 from "../../uploadImg/uploadImg1";
export default function Mine(){
    //上传图片的base64代码
    const [imageBase64, setImageBase64] = useState('');
    //控制对话框的状态
    const [isModalOpen, setIsModalOpen] = useState(false);
    //传递获取的个人信息
    const [selfinformation,setSelfinformation]=useState({});
  //获取帖子的数据
  const [posts, setPosts] = useState([]);
  const [page, setPage] = useState(1);
  const [loading, setLoading] = useState(false);
    //关注者的数量
    const [followcount,setFollowcount]=useState(0);
    //关注的数量
    const [bfollowcount,setBfollowcount]=useState(0);
     //导航
     const navigate = useNavigate();
      // 使用 state 来控制下拉框的显示状态
        const [isDropdownVisible, setDropdownVisible] = useState(false);
    //传给用户标签搜索框的下拉框的值
    const [options1, setOptions1] = useState([]);
    //控制添加框中的输入值
    const [value1, setValue1] = useState('');
    //选中下拉框的帖子标签的值
    const [selecttedtagid1, setSelectedTagId1] = useState(1999999999999999999);
    //添加标签后所有标签值（字符串）
    const [typeStr, setTypeStr] = useState([]);
    //添加标签后所有标签值（数字）
    const [typeInt, setTypeInt] = useState([]);
        //控制下拉框的状态
        const  Dropdown=()=>{
                setDropdownVisible(!isDropdownVisible);
        }
        //size
        const [size, setSize] = useState('large'); 
        //编辑个人信息
        const edit=()=>{
                setOpen(true);
               //填充表单信息
                form.setFieldsValue(selfinformation);
        }
    //标签设置
    const settingTag=()=>{
        setOpen1(true);
    }
        //更新抽屉状态
    const [open, setOpen] = useState(false);
    //更新抽屉2状态
    const [open1, setOpen1] = useState(false);
    //表单
    const [form] = Form.useForm();
    const [status1,setStatus1]=useState(false);
    //清空表单的方法
    const clear=()=>{
        form.resetFields();
    }

//为了讲useEffect中获取的图片数据在return中获得
const [imgdata, setImgData] = useState(null);
    //获取标签列表的数据
    const [typelist, setTypeList] = useState([]);

//提交菜单
const onFinish = async(values) => {
        const response = $ModifySelfInfo(values);
        console.log(response);
        // if(roleId){
        //     const {data:{ message, success }}=await $update(values)
        // if(success){
        //     setNotiMsg({type:'success',description:message})
        //     loadList()
        // }else{  
        //     setNotiMsg({type:'error',description:message})
        // }

        // }else{
        //     const {message,success}=await $add(values)
        // if(success){
        //     setNotiMsg({type:'success',description:message})
        //     loadList()
        //     clear()
        // }else{
        //   console.log(message)
        //     setNotiMsg({type:'error',description:message})
        // }
        // }
        
        
      };

     //关闭修改个人信息抽屉
     const onClose = () => {
        clear()//清空表单
        setOpen(false);//关闭抽屉
      };
     //关闭标签设置抽屉
    const onClose1 = () => {
        setOpen1(false);//关闭抽屉
    };

      const fetchData = async () => {
        try {
              //从localstorage中获得token
              const token=localStorage.getItem('token');
              //获取个人信息
          const response = await $getSelfInformation();
          setSelfinformation(response.data);

          //获取个人头像
          const response3=$getImg({ studentId: response.data.studentId.toString() });
          response3.then((result) => {
            if(result.code===1){
              const { data } = result;
              setImgData(data);
            }
            });
            //获取关注者和关注人员的数量
            const response1 = await  $getFollowCount({ studentId: response.data.studentId.toString() });
            setFollowcount(response1.data.follow);
            setBfollowcount(response1.data.fan);
            //获取用户标签列表
            const response2 = await $getTagList({studentId:response.data.studentId.toString()});
            console.log(response2);
            if(response2.code) {
                const extractedValues = response2.data.map(item => item.tagName);
                const extractedValues1 = response2.data.map(item => item.tagId);
                setTypeStr(extractedValues);
                setTypeInt(extractedValues1);
                setTypeList(response2.data);
            }
        } catch (error) {
          console.error("Error fetching data:", error);
        }
      };


      //获取帖子的信息
      const fetchPosts = async () => {
        try {
          const response = await $getMinePosts({page:page.toString(),pageSize:'10'});
          if(response.code===1){
          setPosts(response.data); // 假设响应的数据结构是一个数组
          }
        } catch (error) {
          console.error('Error fetching posts:', error);
        }
      };
      //在页面滑倒最底下时调用函数加载
      const fetchMorePosts = async () => {
        if (loading) return; // 防止重复加载
        try {
          setLoading(true);
          const nextPage = page + 1;
          const response = await $getPosts({page:page.toString(),pageSize:'10'});
          if(response.code) {
              setPosts(prevPosts => [...prevPosts, ...response.data]);
              setPage(nextPage);
          }
        } catch (error) {
          console.error('Error fetching more posts:', error);
        } finally {
          setLoading(false);
        }
      };
      useEffect(() => {
              fetchData();//获取个人信息数据
              fetchPosts();//获取帖子数据
    }, []); // 确保依赖项数组为空或包含正确的依赖项
    //在帖子滑到最底端的时候获取新的posts值
    useEffect(() => {
      const handleScroll = () => {
        // 在这里可以获取到最新的 posts 值
        if (
          window.innerHeight + document.documentElement.scrollTop ===
          document.documentElement.offsetHeight
        ) {
          fetchMorePosts();
        }
      };

      window.addEventListener('scroll', handleScroll);

      return () => {
        window.removeEventListener('scroll', handleScroll);
      };
    }, [posts]);
    //添加标签框下的下拉选择框
    const onSelect2 = (value, option) => {
        // 更新输入框中的值为选中的 tagName
        setValue1(option.label);
        setSelectedTagId1(value);
        // 保存选中的 tagId 到状态量
    };
    //添加标签框的回调函数
    const onChange2 = async (value1) => {
        setValue1(value1);
        const response = await $getSearchTagList({search:value1,page:'0',pageSize:'7'});
        if(response.data) {
            const transformedOptions = response.data.map(item => ({value: item.tagId, label: item.tagName}));
            // 更新下拉框的选项
            setOptions1(transformedOptions);
        }
    };
    //添加标签框点击添加按钮
    const onSearch2=()=>{

        setTypeInt([...typeInt,selecttedtagid1]);
        setTypeStr([...typeStr,value1]);
        const response = $addnewTag({tagId: selecttedtagid1, studentId: selfinformation.studentId.toString()});
        console.log(response);
        if(response.code) {
            setStatus1(!status1);
        }
        setValue1('');
    }
    //点击标签删除按钮
    const handleRemoveTag = (tagIndex) => {
        // 获取要删除的标签的 tagId
        const tagIdToDelete = typeInt[tagIndex];
        const updatedTags = typeStr.filter((_, index) => index !== tagIndex);
        const updatedTags1 = typeInt.filter((_, index) => index !== tagIndex);
        setTypeStr(updatedTags);
        setTypeInt(updatedTags1);
        const response = $deletenewTag({studentId:selfinformation.studentId,tagId:tagIdToDelete});
    };
    //更换头像
    const handlePicture=()=>{
        setIsModalOpen(true);
    }
//点击验证
    const handleOk = () => {
        console.log('严顺');
        setIsModalOpen(false);
        //这里要做验证事件
    };
    //取消验证框
    const handleCancel = () => {
        setIsModalOpen(false);
    };
    //更改头像
    const Modi=async ()=>{
        if(imageBase64){
            console.log(imageBase64);
         let img_data_without_prefix = imageBase64.replace("data:image/png;base64,", "")
            console.log(img_data_without_prefix);
            const response = await $ModifyAvater({imageData:img_data_without_prefix});
            setIsModalOpen(false);
        }
    }

   return(
       <div style={{width:'80vw',marginLeft:'150px',marginTop:'10px'}}>
           <div className='Top' style={{height: '45vh'}}>
               <div className='Topgreen' style={{height: '27vh', backgroundColor: 'rgb(137, 222, 215)'}}></div>
               <div className='Topwhite' style={{height: '18vh', backgroundColor: 'white'}}>
                   <div className='TopWhiteCenter' style={{marginLeft: '250px'}}>
                       <div className="NickName"
                            style={{fontWeight: 'bold', fontSize: '20px'}}>{selfinformation.nickname}</div>
                       <div className='Center' style={{marginTop: '5px',display:'flex',justifyContent:'space-between'}}>
                           <div className='sex&&information'>
                           <Button icon={selfinformation.sex === 'F' ? <WomanOutlined/> : <ManOutlined/>}
                                   style={selfinformation.sex === 'F' ? {
                                       border: 'none',
                                       color: 'rgb(255, 192, 203)'
                                   } : {border: 'none', color: 'rgb(0, 0, 255)'}}></Button>
                           <span>{selfinformation.briefIntroduction}</span>
                           </div>
                          <div className='follow' style={{marginRight:"150px",display:'flex'}}>
                              <div className='f' style={{borderRight:'2px solid rgb(0,0,0)'}}>
                                  <div>
                                      <div style={{marginRight:'20px',color:'rgb(134,133,133)'}}>关注</div>
                                      <div style={{fontWeight:'bold',marginLeft:'6px',fontSize:'20px'}}>{bfollowcount}</div>
                                  </div>

                              </div>
                              <div className='bf' style={{marginLeft:'20px'}}>
                                  <div style={{color:'rgb(134,133,133)'}}>关注者</div>
                                  <div style={{fontWeight:'bold',marginLeft:'12px',fontSize:'20px'}}>{followcount}</div>
                              </div>
                          </div>
                       </div>
                       <div style={{display: 'flex', marginTop: '10px'}}>
                       {typelist.map((tag, index) => (
                               <span key={index} style={{
                                   marginLeft: '30px',
                                   backgroundColor: 'rgb(88, 209, 200)',
                                   color: 'white',
                                   borderRadius: '15px',
                                   padding: '5px'
                               }}>
                                <span>{tag.tagName}</span>
                            </span>
                           ))}
                       </div>
                        <div style={{position: 'absolute', top: '49vh', left: '72.5vw',zIndex: 999}} >
                            <Button style={{border:'none'}} icon={<SettingOutlined />}onClick={settingTag} >设置标签</Button>
                        </div>
                   </div>
               </div>
               <div className='picture' style={{position: 'relative', top: '-21vh', left: '5vw',width:'130px', height:'130px'}} onClick={handlePicture}>
                   <img src={`data:image/jpeg;base64,${imgdata}`} width='130px' height="130px"  alt="获取图片失败"/>
               </div>

           </div>
           <div className='Bottom' style={{marginTop:'10px',minHeight:'100vh',display:'flex'}}>
                <div className='Bottom-left' style={{width:'60vw',backgroundColor:'white',minHeight:'100vh'}}>
                    {posts.map((post, index) => (
                        <Post key={index} post={post} avater={imgdata}/>
                    ))}
                </div>
               <div className='Bottom-right' style={{width:'20vw',backgroundColor:'white',height:'350px',marginLeft:'10px'}}>
                   <div className='selfinformation'>
                       <div className='top' style={{display:'flex',justifyContent:'space-between',marginTop:'20px'}}>
                        <div style={{color:'rgb(138, 223, 216)',fontWeight:'bold',fontSize:'15px',marginLeft:'20px'}}>个人资料</div>
                           <Button  style={{ backgroundColor:'rgb(138, 223, 216)', color: 'white',marginRight:'20px'}}
                                   onClick={edit}>编辑</Button>
                       </div>
                       <div className='Bottom'>
                           <div style={{marginLeft: '20px', marginTop: '20px'}}>
                               <span>昵称：</span>
                               <span>{selfinformation.nickname}</span>
                           </div>
                           <div style={{marginLeft: '20px', marginTop: '20px'}}>
                               <span>性别：</span>
                               <span>{selfinformation.sex === 'F' ? '女' : '男'}</span>
                           </div>
                           <div style={{marginLeft: '20px', marginTop: '20px'}}>
                               <span>生日：</span>
                               <span>{selfinformation.birthday}</span>
                           </div>
                           <div style={{marginLeft: '20px', marginTop: '20px'}}>
                               <span>邮件：</span>
                               <span>{selfinformation.email}</span>
                           </div>
                           <div style={{marginLeft: '20px', marginTop: '20px'}}>
                               <span>公司：</span>
                               <span>{selfinformation.currentCompany}</span>
                           </div>
                           <div style={{marginLeft: '20px', marginTop: '20px'}}>
                               <span>职位：</span>
                               <span>{selfinformation.position}</span>
                           </div>
                           <div style={{marginLeft: '20px', marginTop: '20px'}}>
                               <span>个人简介：</span>
                               <span>{selfinformation.brief_introduction}</span>
                           </div>
                       </div>
                   </div>
               </div>
           </div>
           <Drawer title='修改个人信息' width={500} placement="right" onClose={onClose} open={open}>

               <Form
                   form={form}
                   name="basic"
                   labelCol={{
                       span: 4,
                   }}
                   wrapperCol={{
                       span: 18,
                   }}
                   style={{
                       maxWidth: 600,
                   }}
                   onFinish={onFinish}
                   autoComplete="off"
               >

                   <Form.Item
                       label="生日"
                       name="birthday"
                       rules={[
                           {
                               required: false,
                               message: '请输入您的生日',
                           },
                       ]}
                   >
                       <Input/>
                   </Form.Item>
                   <Form.Item
                       label="个人简介"
                       name="briefIntroduction"
                       rules={[
                           {
                               required: false,
                               message: '请输入个人简介',
                           },
                       ]}
                   >
                       <Input/>
                   </Form.Item>

                   <Form.Item
                       label="昵称"
                       name="nickname"
                       rules={[
                           {
                               required: false,
                               message: '请输入您的昵称',
                           },
                       ]}
                   >
                       <Input/>
                   </Form.Item>
                   <Form.Item
                       label="就职公司"
                       name="currentCompany"
                       rules={[
                           {
                               required: false,
                               message: '请输入当前就职公司',
                           },
                       ]}
                   >
                       <Input/>
                   </Form.Item>

                   <Form.Item
                       label="职位"
                       name="position"
                       rules={[
                           {
                               required: false,
                               message: '请输入您的职位',
                           },
                       ]}
                   >
                       <Input/>
                   </Form.Item>


                   <Form.Item
                       wrapperCol={{
                           offset: 4,
                           span: 16,
                       }}
                   >
                       <Button type="primary" htmlType="submit">
                           修改
                       </Button>
                       <Button onClick={clear} style={{marginLeft: '10px'}}>
                           取消
                       </Button>
                   </Form.Item>
               </Form>
           </Drawer>
           <Drawer title='个人标签设置' width={500} placement="left" onClose={onClose1} open={open1}>
               <div style={{display: 'flex', marginTop: '10px',flexWrap:'wrap'}}>
                   {typeStr.map((tag, index) => (
                       <span key={index} style={{
                           marginRight:'20px',
                           backgroundColor: 'rgb(88, 209, 200)',
                           color: 'white',
                           borderRadius: '15px',
                           padding: '5px',
                           marginBottom:'20px'
                       }}>
                                <span>{"# " + tag}</span>
                                <Button onClick={() => handleRemoveTag(index)} icon={<CloseCircleOutlined/>}
                                        style={{
                                            border: 'none',
                                            width: '20px',
                                            height: '30px',
                                            backgroundColor: 'rgb(88, 209, 200)',
                                            color: 'white'
                                        }}></Button>
                            </span>
                   ))}
               </div>
               <div>
               <AutoComplete
                   options={options1}
                   style={{width: '380px', height: '30px',marginTop:'60px'}}
                   onSelect={onSelect2}
                   onChange={onChange2}
                   value={value1}
                   placeholder="搜索标签"
               />
               <Button icon={<PlusOutlined/>} style={{color: 'rgb(88, 209, 200)'}}
                       onClick={() => onSearch2(value1)}></Button>
               </div>
           </Drawer>
           <Modal title="更改头像" visible={isModalOpen} onOk={handleOk} onCancel={handleCancel} footer={null}  style={{ zIndex: 99999 }} >
               <UploadImg1 setImageBase64={setImageBase64} imageBase64={imageBase64} />
               <Button onClick={Modi}>更改</Button>
           </Modal>
       </div>
   )
}